<template>
  <SelectionDialog ref="selectionDialogRef" v-model="dialogVisible" :config="judgeConfig" :optional-data="optionalJudges"
    :confirm-loading="judgeLoading" :selected-data="selectedJudges" :data-loading="dataLoading" width="904px" @confirm="handleConfirm" :role="role"
    @cancel="handleCancel" @selectedListChange="handleSelectedListChange">
    <template #header>
      <div class="flex items-center pb-[24px] mb-[16px] border-b">
        <span class="text-red-500 w-[60px] mr-[4px] text-right">*</span>
        <span class="whitespace-nowrap mr-[12px]">{{ $t('trackMgr.role') }}</span>
        <el-select v-model="role" :placeholder="$t('trackMgr.selectRole')" clearable class="w-[300px] mr-[24px]"
          @change="handleRoleConfirm">
          <el-option v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-button @click="handleRoleReset">{{ $t('trackMgr.reset') }}</el-button>
        <el-button type="primary" @click="handleRoleConfirm">{{ $t('trackMgr.confirm') }}</el-button>
      </div>
    </template>
  </SelectionDialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, h } from 'vue'
import { ElMessage } from 'element-plus'
import { $t } from '@vben/locales'
import SelectionDialog from './selection-dialog.vue'
import { updateCompTrackStatusApi } from '#/api/competition/track-mgr'
import { getRolePageApi } from '#/api/system/role'
import { getUserInfoByRoleApi, getUserInfoByIdsApi } from '#/api/system/user'

// 评委数据接口
interface Judge {
  id: number | string
  name: string
  unit: string
  [key: string]: any
}

// Props 定义
interface Props {
  modelValue: boolean
  trackId?: number | string
  selectedJudgeIds?: (number | string)[]
  mode?: 'add' | 'edit' // 新增模式参数
}

const props = withDefaults(defineProps<Props>(), {
  selectedJudgeIds: () => [],
  mode: 'add'
})

// Emits 定义
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'confirm': []
  'cancel': []
}>()

// 评委选择配置 - 使用计算属性动态设置标题
const judgeConfig = computed(() => ({
  title: props.mode === 'edit'
    ? $t('trackMgr.editJudgesTitle')
    : $t('trackMgr.setJudgesTitle'),
  searchPlaceholder: $t('userMessage.searchPlaceholder'),
  columns: [
    { prop: 'userName', label: $t('trackMgr.judgeName'), minWidth: '100px' },
    {
      prop: 'roles', label: $t('system.role.role'), minWidth: '150px', render:
        (row: any, type: any) => {
          return h('span', (row.roles?.length > 0 ?
            (type === 'left' ? row.roles.filter((role: string) => role === roleSelectedName.value).join(',') : row.roles.join(',')) :
            '--')
          )
        }
    },
  ],
  type: 'judge' as const
}))

// 响应式数据
const loading = ref(false)
const judgeLoading = ref(false)
const dataLoading = ref(false) // 数据加载状态
const allJudges = ref<Judge[]>([])
const selectedJudges = ref<Judge[]>([])
const selectionDialogRef = ref() // 选择对话框引用

// 角色选择相关
const role = ref('')
const roleConfirmed = ref(false) // 新增：标记是否已确认角色选择

// 角色操作方法
const handleRoleReset = () => {
  role.value = ''
  roleConfirmed.value = false
  allJudges.value = [] // 清空可选评委列表
}

const roleSelectedName = ref('')
const handleRoleConfirm = async () => {
  roleSelectedName.value = roleList.value.find(item => item.value === role.value)?.label || ''
  // 根据选择的角色获取可选数据
  if (role.value) {
    roleConfirmed.value = true
    dataLoading.value = true

    // 通知子组件开始加载数据
    if (selectionDialogRef.value) {
      selectionDialogRef.value.setOptionalLoading(true)
    }

    try {
      const res = await getUserInfoByRoleApi({ id: role.value })
      if (res.length > 0) {
        allJudges.value = res.map((item: any) => {
          item.id = item.userId
          return item
        })
      } else {
        allJudges.value = []
      }
    } catch (error) {
      console.error('获取角色用户信息失败:', error)
      ElMessage.error('获取角色用户信息失败，请重试')
      allJudges.value = []
    } finally {
      dataLoading.value = false
      // 通知子组件结束加载数据
      if (selectionDialogRef.value) {
        selectionDialogRef.value.setOptionalLoading(false)
      }
    }
  } else {
    ElMessage.warning($t('trackMgr.selectRoleFirst'))
  }
}
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 可选评委列表（只有在角色确认后才显示，并排除已选的）
const optionalJudges = computed(() => {
  if (!roleConfirmed.value) {
    return [] // 未确认角色时返回空数组
  }
  return allJudges.value.filter(judge =>
    !selectedJudges.value.some(selected => selected.id === judge.id)
  )
})

// 处理已选择列表变化
const handleSelectedListChange = (selectedItems: any[]) => {
  selectedJudges.value = selectedItems
}

const roleList = ref<any[]>([])

// 获取角色下拉列表和已选评委数据
const getPageInfo = async () => {
  loading.value = true
  dataLoading.value = true

  try {
    // 获取角色列表
    const roleRes = await getRolePageApi({ status: 'enable' })
    roleList.value = roleRes.data?.map((item: any) => {
      return {
        label: item.name,
        value: item.id
      }
    }) || []

    // 获取已选评委数据（这部分不受角色选择影响）
    if (props.selectedJudgeIds && props.selectedJudgeIds.length > 0) {
      const judgeRes = await getUserInfoByIdsApi(props.selectedJudgeIds)
      if (judgeRes.length > 0) {
        selectedJudges.value = judgeRes.map((item: any) => {
          item.id = item.userId
          return item
        })
      } else {
        selectedJudges.value = []
      }
    } else {
      selectedJudges.value = []
    }
  } catch (error) {
    console.error('获取页面信息失败:', error)
    ElMessage.error('获取页面信息失败，请重试')
  } finally {
    loading.value = false
    dataLoading.value = false
  }
}

// 重置页面状态
const resetPageState = () => {
  role.value = ''
  roleConfirmed.value = false
  allJudges.value = []
  // 清空子组件数据
  if (selectionDialogRef.value) {
    selectionDialogRef.value.clearAllData()
  }
}

// 确认选择
const handleConfirm = async (selectedItems: any[]) => {
  if (!props.trackId) {
    ElMessage.error($t('trackMgr.trackIdRequired'))
    return
  }

  judgeLoading.value = true
  try {
    const data = {
      id: props.trackId,
      expertJudgeList: selectedItems.map(judge => judge.id)
    }
    await updateCompTrackStatusApi(data)
    ElMessage.success($t('trackMgr.judgeSetSuccess'))
    emit('confirm')
    emit('update:modelValue', false)
  } catch (error) {
    // ElMessage.error('评委设置失败，请重试！')
    // console.error('设置评委失败:', error)
  } finally {
    judgeLoading.value = false
  }
}

// 取消选择
const handleCancel = () => {
  emit('cancel')
  emit('update:modelValue', false)
}

// 监听弹窗打开，获取数据并重置状态
watch(() => props.modelValue, (newValue) => {
  if (newValue) {
    resetPageState() // 每次打开弹窗时重置状态
    getPageInfo()
  }
})

// 组件挂载时获取数据
onMounted(() => {
  if (props.modelValue) {
    resetPageState()
    getPageInfo()
  }
})
</script>
